package com.bci.pwtz.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.CookieUtil;
import com.bci.pwtz.common.util.ExcelUtil;
import com.bci.pwtz.common.util.JsonUtils;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.common.util.SHA256Cryptor;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.exception.VerifyCodeIsBusyException;
import com.bci.pwtz.exception.VisitCountIsOverTheLimitException;
import com.bci.pwtz.mysql.dao.CompanyUserRoleMapper;
import com.bci.pwtz.mysql.model.Company;
import com.bci.pwtz.mysql.model.CompanyRole;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.CompanyUserAudit;
import com.bci.pwtz.mysql.model.CompanyUserRole;
import com.bci.pwtz.mysql.model.RandomCode;
import com.bci.pwtz.mysql.model.SmsSendLog;
import com.bci.pwtz.mysql.model.UserCompanyRef;
import com.bci.pwtz.service.CompanyRoleService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.CompanyUserAuditService;
import com.bci.pwtz.service.CompanyUserService;
import com.bci.pwtz.service.SmsSendLogService;
import com.bci.pwtz.service.UserCompanyRefService;
import com.bci.pwtz.service.VerifyCodeService;
import com.bci.pwtz.service.sms.SendSmsService;



/**
 * 用户控制器controller <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 包含以下功能 <br/>
 * 登陆 <br/>
 * 
 * <PRE>
 *      /user/${actionName}
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/user/companyuser")
public class CompanyUserController extends AbstractController
{
    @Autowired
    private CompanyUserService     companyUserService;
    @Autowired
    private CompanyService     companyService;
    @Autowired
    private VerifyCodeService     verifyCodeService;
    @Autowired
    private SendSmsService     sendSmsService;
    @Autowired
    private SmsSendLogService     smsSendLogService;
    @Autowired
    private CompanyUserAuditService     companyUserAuditService;
    @Autowired
    private CompanyRoleService     companyRoleService;
    @Autowired
    UserCompanyRefService userCompanyRefService;
    @Autowired
    CompanyUserRoleMapper companyUserRoleMapper;
    /**
     * 
     * 执行登录操作(异步请求) <br/>
     * <p>
     * Description: 执行登录操作,登录成功后记录用户信息到session <br/>
     * <p>
     * Author: huangb<br/>
     * <p>
     * Date: 2014-9-12-下午4:09:11<br/>
     * <p>
     * 
     * @param session
     * @param loginName
     * @param pwd
     * @param imageCode
     * @return
     * 
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> login(HttpServletRequest req,HttpServletResponse resp,String loginName, String pwd, String imageCode,String status)
    {
        String imageCodeSession = (String) session.getAttribute("imageCode");
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
            if ((StringUtils.isNotBlank(imageCodeSession) && imageCodeSession.equalsIgnoreCase(imageCode)))
            {
                pwd = SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY+pwd);
                System.out.println("login: loginName="+loginName+"|pwd="+pwd);
                CompanyUser user = companyUserService.findUserInfo(loginName,pwd);
                if (null != user)
                {
                    Long userId = user.getCompanyUserId();
                    session.setAttribute("user", user);
                    session.setAttribute("userId", userId);
                    List<String> actionList=getCurrentAction();
                    session.setAttribute("actionList", actionList);
                    if(getLastCompanyId()!=null){
                    session.setAttribute("isSuper", companyRoleService.checkIsCreator(userId, getLastCompanyId()));
                    }
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,
                            "登录成功");
                    if("1".equals(status)){
                        CookieUtil.rocordAccountCookie(req,resp,loginName,pwd);
                    }
                }
                else
                {
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                            "VisitInvalidParametersException", "用户名不存在或密码错误！");
                }
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "ErrorImageCode", "验证码错误！");
            }
        }
        catch (PwtzException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
        	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "errorCode", "系统错误！");
        }
        session.removeAttribute("imageCode");

        return respMap;
    }
    /**
     * 执行登出操作
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月28日-下午3:10:46<br/>
     * <p>
     * @param userId
     * @return   
     *
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public void logout(HttpServletRequest req,HttpServletResponse resp,String loginUrl)
    {
        if(session.getAttribute("userId")!=null)
        {
            session.removeAttribute("userId");
            session.removeAttribute("user");
            session.removeAttribute("isSuper");
            CookieUtil.removeAccountCookie(req,resp);
            
        }
        try
        {
            resp.sendRedirect(loginUrl+"?t="+System.currentTimeMillis());
            
        }
        catch (IOException e)
        { }
    }
    /**
     * 执行创建邀请码操作
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月28日-下午3:11:54<br/>
     * <p>
     * @param companyId
     * @param companyRoleId
     * @return   
     *
     */
    @RequestMapping(value = "/createrandomcode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> createRandomCode()
    {
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
            Long companyId = getLastCompanyId();
            CompanyRole cr=companyRoleService.selectDefault(companyId);
            Long companyRoleId = cr.getCompanyRoleId();
            String rcode="";
            List<RandomCode> list=companyUserService.getCompanyRandomCode(companyId);
            if(list!=null&&list.size()>0){
                rcode=list.get(0).getRandomCode();
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_INFO,null,"邀请码已创建,勿重复创建");
                respMap.put("randomCode", rcode);
            }else{
                rcode=companyUserService.createRandomCode(companyId, companyRoleId);
                if(StringUtils.isNotEmpty(rcode)){
                    respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,"创建邀请码成功");
                    respMap.put("randomCode", rcode);
                }else{
                    respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"创建邀请码失败");
                }
            }
        }
        catch (NumberFormatException e)
        {
            respMap=packageException(e);
        }
        catch (PwtzDatabaseException e)
        {
            respMap=packageUppException(e);
        }
        return respMap;
    }
    /**
     * 执行获取短信验证码操作
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月28日-下午3:11:05<br/>
     * <p>
     * @param mobile
     * @param type
     * @return   
     *
     */
    @RequestMapping(value = "/getcode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> getCode(String mobile,int type,String imageCode)
    {
    	String imageCodeSession = (String) session.getAttribute("imageCode");
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
        	if ((StringUtils.isNotBlank(imageCodeSession) && imageCodeSession.equalsIgnoreCase(imageCode)))
            {
	            int ret=companyUserService.selectCountByMobile(mobile);
	            if(type==1){
	                if(ret>0){
	                    respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"手机号码已注册");
	                    return respMap;
	                }
	            }
	            if(type==2){
	                if(ret==0){
	                    respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"手机号码不存在");
	                    return respMap;
	                }
	            }
	            String code = verifyCodeService.getCode(mobile,type);
	            if(code!=null){
	                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS,ERROR_VALUE_MSG_TYPE_INFO,null,"获取验证码成功");
	                String msg = MessageFormat.format(PwtzConstants.GET_SWITCH_TEL_CODE_MSG, code);
	                String[] mobiles=new String[]{mobile};
	                sendSmsService.batchSend(mobiles, msg, null, null);
	            }else{
	                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"获取验证码失败");
	            }
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "ErrorImageCode", "验证码错误！");
            }
        }
        catch (NumberFormatException e)
        {
            respMap=packageException(e);
        }
        catch (PwtzDatabaseException e)
        {
            respMap=packageUppException(e);
        }
        catch (VerifyCodeIsBusyException e)
        {
            respMap=packageException(e);
        }
        catch (VisitCountIsOverTheLimitException e)
        {
            respMap=packageException(e);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (PwtzException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return respMap;
    }
    /**
     * 执行注册操作
     * 一句话描述 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: Administrator<br/>
     * <p>Date: 2014年9月28日-下午3:11:32<br/>
     * <p>
     * @param loginName
     * @param mobile
     * @param code
     * @param pwd
     * @param randomCode
     * @param userName
     * @return   
     *
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> register(String loginName, String mobile, String code, String pwd, String randomCode, String userName)
    {
        Map<String, String> respMap = new HashMap<String, String>();
        try
        {
            int ret = companyUserService.selectCountByName(loginName);
            if (ret > 0)
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "用户名已被注册");
                return respMap;
            }
            ret = companyUserService.selectCountByMobile(mobile);
            if (ret > 0)
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "手机号已被注册");
                return respMap;
            }
            ret = verifyCodeService.validateCode(mobile, code);
            if(ret==0)
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "短信验证码不正确");
                return respMap;
            }
            CompanyUser cuser = new CompanyUser();
            cuser.setLoginName(loginName);
            cuser.setMobile(mobile);
            cuser.setUserName(userName);
            cuser.setLoginPwd(SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY+pwd));
            RandomCode rcode = null;
            if (StringUtils.isNotBlank(randomCode))
            {
                rcode = companyUserService.selectRandomCode(randomCode);
                if (rcode == null)
                {
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "邀请码无效");
                    return respMap;
                }
                else
                {
                    if (rcode.getCompanyId() != null)
                    {
                        cuser.setLastCompanyId(rcode.getCompanyId());
                        cuser = companyUserService.register(cuser);
                    }
                    else
                    {
                        cuser = companyUserService.register(cuser);
                    }
                    if (rcode.getCompanyId() != null)
                    {
                        UserCompanyRef ref = new UserCompanyRef();
                        ref.setCompanyId(rcode.getCompanyId());
                        ref.setCompanyUserId(cuser.getCompanyUserId());
                        companyUserService.addUserCompanyRef(ref);
                    }
                    if (rcode.getCompanyId() != null)
                    {
                        CompanyUserRole role = new CompanyUserRole();
                        role.setCompanyRoleId(rcode.getCompanyRoleId());
                        role.setCompanyUserId(cuser.getCompanyUserId());
                        companyUserService.addCompanyUserRole(role);
                    }
                }
            }
            else
            {
                cuser = companyUserService.register(cuser);
            }
            if (cuser != null)
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "注册成功");
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "注册失败");
            }

        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value = "/modifypassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> modifyPassword(String oldpassword,String password)
    {
    	Map<String, String> respMap = new HashMap<String, String>();
        try
        {
            if(StringUtils.isEmpty(oldpassword) ||StringUtils.isEmpty(password)){
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "参数错误");
                return respMap;
            }
            long companyUserId = (Long)session.getAttribute("userId");
            //String companyUserId = "1";
            oldpassword = SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + oldpassword);
            //System.out.println("oldpassword="+oldpassword);
            int res = companyUserService.selectCountByPassword(companyUserId, oldpassword);
            if (res == 0){
            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "旧密码输入不正确");
                return respMap;
            }
            CompanyUser companyUser = new CompanyUser();
            companyUser.setCompanyUserId(Long.valueOf(companyUserId));
            companyUser.setLoginPwd(SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password));
            int result = companyUserService.update(companyUser);
            if (result>0)
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"密码修改成功");
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "密码修改失败");
            }

        }
        catch (PwtzDatabaseException e)
        {
        	respMap = packageUppException(e);
        }
        catch (Exception e)
        {
        	respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value = "/forgetpassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> forgetPassword(String mobile,String code/*,String imageCode*/)
    {
//    	String imageCodeSession = (String) session.getAttribute("imageCode");
    	Map<String, String> respMap = new HashMap<String, String>();
        try
        {
//        	if ((StringUtils.isNotBlank(imageCodeSession) && imageCodeSession.equalsIgnoreCase(imageCode))){
//	            if(StringUtils.isEmpty(mobile) ||StringUtils.isEmpty(code) ||StringUtils.isEmpty(imageCode)){
//	                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "参数错误");
//	                return respMap;
//	            }
	            int isMobile = companyUserService.selectCountByMobile(mobile);
	            if (isMobile == 0){
	            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "电话号码不存在");
	                return respMap;
	            }
	            int res = verifyCodeService.validateCode(mobile, code);
	            if (res == 0){
	            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "手机验证码错误！");
	                return respMap;
	            }
	            //String companyUserId = (String)session.getAttribute("userId");
	            //String companyUserId = "2";
	            String newPassword = PwtzConstants.PASSWORD_KEY + PwtzUtils.getRandomNumber(6);
	            //System.out.println("newPassword="+newPassword);
	            //CompanyUser companyUser = new CompanyUser();
	            //companyUser.setCompanyUserId(Long.valueOf(companyUserId));
	            //companyUser.setLoginPwd(SHA256Cryptor.sha256Encrypt(newPassword));
	            int result = companyUserService.updatePwdByMobile(SHA256Cryptor.sha256Encrypt(newPassword), mobile);
	            if (result>0)
	            {
	                newPassword=newPassword.substring(PwtzConstants.PASSWORD_KEY.length());
	                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"密码修改成功");
	                String msg = MessageFormat.format(PwtzConstants.MODIFIED_PASSWORD_MSG, newPassword);
	                String[] mobiles=new String[]{mobile};
	                String smsReturn = sendSmsService.batchSend(mobiles, msg, null, null);
	                if("0".equals(smsReturn) || "1".equals(smsReturn)){
	                	SmsSendLog smsSendLog = new SmsSendLog();
	                	smsSendLog.setMobile(mobile);
	                	smsSendLog.setContent(msg);
	                	smsSendLogService.add(smsSendLog);
	                }
	            }
	            else
	            {
	                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "密码修改失败");
	            }
//        	}else{
//        		respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorImageCode", "验证码错误！");
//        	}

        }
        catch (PwtzDatabaseException e)
        {
        	respMap = packageUppException(e);
        }
        catch (Exception e)
        {
        	respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> edit(String userName)
    {
        Map<String, String> respMap = new HashMap<String, String>(2);
        try
        {
            if(userName.length()>10){
                return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "VisitInvalidParametersException", "名称超长！");
            }
            Long userId = (Long)session.getAttribute("userId");

            CompanyUser user = companyUserService.load(userId);
            if (null != user)
            {
                user.setUserName(userName);
                int ret =companyUserService.update(user);
                if(ret>0){
                    session.setAttribute("user", user);
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,
                        "修改用户信息成功");
                }else{
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                            "VisitInvalidParametersException", "修改用户信息失败！");
                }
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                        "VisitInvalidParametersException", "用户不存在！");
            }
        }
        catch (PwtzException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value = "/addcompany", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> addcompany(long companyid)
    {
    	Map<String, String> respMap = new HashMap<String, String>();
        try
        {
            long companyUserId = (Long)session.getAttribute("userId");
            int res = companyUserAuditService.selectByUserId(companyUserId,companyid);
            //System.out.println("res="+res);
            if (res == 1){
            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "您已经申请过，请等待审核");
                return respMap;
            }
            int joinCompanyNumByUserId=userCompanyRefService.selectJoinCompanyNumByUserId(companyUserId);
            if(joinCompanyNumByUserId >= PwtzConstants.MAX_JOIN_COMPANY_COUNT){
            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "您加过的公司已经超过最大值");
                return respMap;
            }
            boolean isVip =  companyService.isVip(companyid);
            if(!isVip){
                int companyUsers = userCompanyRefService.selectCompanyUsers(companyid);
                if(companyUsers>=PwtzConstants.THE_TRIAL_USERS_COUNT){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "你申请加入的单位员工数已满");
                    return respMap;
                }
            }
            CompanyUserAudit companyUserAudit = new CompanyUserAudit();
            companyUserAudit.setCompanyUserId(companyUserId);
            companyUserAudit.setCompanyId(companyid);
            companyUserAudit.setResult(1);
            CompanyUserAudit result = companyUserAuditService.add(companyUserAudit);
            if (result != null)
            {
                companyService.sendJoinCompanyValidateSms(companyUserId, companyid, result.getAuditId());
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"申请成功，请等待审核");
            }
            else
            {
            	respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "申请失败，请重新申请");
            }

        }
        catch (PwtzDatabaseException e)
        {
        	respMap = packageUppException(e);
        }
        catch (Exception e)
        {
        	respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value="/userrolelist",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<CompanyUser> userrolelist(long companyRoleId,int pageszie,int pagenum) throws PwtzException{
        
        PaginationList<CompanyUser> list = new PaginationList<CompanyUser>();
        try
        {
            list=companyUserService.selectUserByRole(companyRoleId, pageszie, pagenum);
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        
        return list;
    }
    
    
    
    @RequestMapping(value="/userlist",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<CompanyUser> userlist(long companyRoleId, String loginname, int pageszie,int pagenum) throws PwtzException{
        
        PaginationList<CompanyUser> list = new PaginationList<CompanyUser>();
        try
        {
            CompanyUser user = (CompanyUser)session.getAttribute("user");
            //System.out.println("user.getLastCompanyId()="+user.getLastCompanyId());
            list=companyUserService.selectUseByLastCompanyId(companyRoleId, user.getLastCompanyId(), loginname, pageszie, pagenum);
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        
        return list;
    }
    
    @RequestMapping(value = "/userroleadd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> userroleadd(long roleid, String userid)
    {
        Map<String, String> respMap = new HashMap<String, String>();
        try
        {
            CompanyUser user=(CompanyUser) session.getAttribute("user");
            Long companyId=user.getLastCompanyId();
            String[] useridstr = userid.split(",");
            for(int i=0;i<useridstr.length;i++){
            	    List<CompanyUserRole> list=companyUserRoleMapper.selectCompanyUserRole(companyId, Long.valueOf(useridstr[i]));
            	    if(list!=null&&list.size()>0){
            	        CompanyUserRole userRole = list.get(0);
                        userRole.setCompanyRoleId(roleid);
                        companyUserRoleMapper.updateByPrimaryKey(userRole);
            	    }else{
            	        CompanyUserRole userRole = new CompanyUserRole();
                        userRole.setCompanyUserId(PwtzUtils.passLong(useridstr[i]));
                        userRole.setCompanyRoleId(roleid);
                        companyUserService.addCompanyUserRole(userRole);
            	    }
            }
            respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "添加成功");

        }
        catch (PwtzDatabaseException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }
    
    
    @RequestMapping(value = "/userroledel", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> userroledel(long roleid, long userid)
    {
        Map<String, String> respMap = new HashMap<String, String>();
        try
        {
            int result = companyUserService.deleteCompanyUserRoleByUserId(userid, roleid);
            if (result ==1 )
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"删除成功");
            }
            else
            {
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "删除失败");
            }

        }
        catch (PwtzDatabaseException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }

  //用户名是否已被注册
        @RequestMapping(value = "/getLoginNameCount", method = RequestMethod.POST)
        @ResponseBody
        public Map<String, String> getLoginNameCount(String loginName)
        {
            Map<String, String> respMap = new HashMap<String, String>();
            try
            {
                int count = companyUserService.selectCountByName(loginName);
                respMap.put(ERROR_KEY_OP_RESULT, ERROR_VALUE_OP_RESULT_SUCCESS);
                respMap.put("count", String.valueOf(count));    
            }
            catch (PwtzDatabaseException e)
            {
                respMap = packageUppException(e);
            }
            catch (Exception e)
            {
                respMap = packageException(e);
            }
            return respMap;
        }
      //手机号是否已被注册
        @RequestMapping(value = "/getMobileCount", method = RequestMethod.POST)
        @ResponseBody
        public Map<String, String> getMobileCount(String mobile)
        {
            Map<String, String> respMap = new HashMap<String, String>();
            try
            {
                int count = companyUserService.selectCountByMobile(mobile);  
                respMap.put(ERROR_KEY_OP_RESULT, ERROR_VALUE_OP_RESULT_SUCCESS);
                respMap.put("count", String.valueOf(count));    
            }
            catch (PwtzDatabaseException e)
            {
                respMap = packageUppException(e);
            }
            catch (Exception e)
            {
                respMap = packageException(e);
            }
            return respMap;
        }
    @RequestMapping(value = "/changemobile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> changeMobile(String password,String mobile,String code)
    {
        Map<String, String> respMap = new HashMap<String, String>();
        try
        {
                if(StringUtils.isEmpty(mobile) ||StringUtils.isEmpty(code) || StringUtils.isEmpty(password)){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ParametersException", "参数错误");
                    return respMap;
                }
                int isMobile = companyUserService.selectCountByMobile(mobile);
                if (isMobile > 0){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "电话号码已存在");
                    return respMap;
                }
                int res = verifyCodeService.validateCode(mobile, code);
                if (res == 0){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "手机验证码错误");
                    return respMap;
                }
                long companyUserId = (Long)session.getAttribute("userId");
                
                password = SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password);
                int ret = companyUserService.selectCountByPassword(companyUserId,password);
                if (res > 0){
                    CompanyUser user = companyUserService.load(companyUserId);
                    user.setCompanyUserId(companyUserId);
                    user.setMobile(mobile);
                    ret = companyUserService.update(user);
                    if(ret>0){
                        respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"手机号码变更成功");
                        session.setAttribute("user", user);
                    }else{
                        respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "手机号码变更失败");
                    }
                }else{
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "原密码错误");
                }

        }
        catch (PwtzDatabaseException e)
        {
            respMap = packageUppException(e);
        }
        catch (Exception e)
        {
            respMap = packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value="/list",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<CompanyUser> list(int pageNo) throws PwtzException{
        PaginationList<CompanyUser> list = new PaginationList<CompanyUser>();
        try
        {
            CompanyUser user = (CompanyUser)session.getAttribute("user");
            list=companyUserService.selectUseByCompanyId(user.getLastCompanyId(), getPageSize(), pageNo);
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        return list;
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> add(String loginName,String mobile,String userName){
        Map<String, String> respMap = new HashMap<String, String>(2);
        try{
            CompanyUser companyUser = (CompanyUser)session.getAttribute("user");
            Long companyId = companyUser.getLastCompanyId();
            boolean isVip =  companyService.isVip(companyId);
            if(!isVip){
                int companyUsers = userCompanyRefService.selectCompanyUsers(companyId);
                if(companyUsers>=PwtzConstants.THE_TRIAL_USERS_COUNT){
                    respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,null, "单位员工数已满");
                    return respMap;
                }
            }
            if(StringUtils.isEmpty(loginName)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"用户名为空");
                return respMap;
            }
            if(!PwtzUtils.isName(loginName)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"用户名必须为6-20位字母或数字");
                return respMap;
            }
            if(StringUtils.isEmpty(mobile)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"电话号码为空");
                return respMap;
            }
            if(!PwtzUtils.isMobile(mobile)){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"电话号码错误");
                return respMap;
            }
            CompanyUser olduser=companyUserService.selectUser(loginName,mobile);
            if(olduser!=null&& olduser.getCompanyUserId()>0){
                    Long userId = olduser.getCompanyUserId();
                    int ret = userCompanyRefService.selectInCompany(userId, companyId);
                    if(ret==0){
                        respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"添加用户成功");
                        if(companyId>0){
                            UserCompanyRef ref=new UserCompanyRef();
                            ref.setCompanyId(companyId);
                            ref.setCompanyUserId(userId);
                            companyUserService.addUserCompanyRef(ref);
                        }
                        CompanyRole companyRole=companyRoleService.selectDefault(companyId);
                        if(companyRole!=null){
                            CompanyUserRole ref = new CompanyUserRole();
                            ref.setCompanyRoleId(companyRole.getCompanyRoleId());
                            ref.setCompanyUserId(userId);
                            companyUserService.addCompanyUserRole(ref);
                        }
                        return respMap;
                    }else{
                        respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null,"用户已加入该公司");
                        return respMap;
                    }
            }
            int ret=companyUserService.selectCountByName(loginName);
            if(ret>0){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"用户名已被注册");
                return respMap;
            }
            ret=companyUserService.selectCountByMobile(mobile);
            if(ret>0){
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"手机号已被注册");
                return respMap;
            }
            CompanyUser cuser=new CompanyUser();
            cuser.setLoginName(loginName);
            cuser.setMobile(mobile);
            cuser.setUserName(userName);
            cuser.setLastCompanyId(companyId);
            String password = PwtzUtils.getRandomNumber(6);
            cuser.setLoginPwd(SHA256Cryptor.sha256Encrypt(PwtzConstants.PASSWORD_KEY + password));

            cuser = companyUserService.register(cuser);
            if (cuser!=null && cuser.getCompanyUserId()>0)
            {
                Long userId = cuser.getCompanyUserId();
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"添加用户成功");
                String smsReturn = sendSmsService.batchSend(mobile.split(","), "用户名为:"+loginName+"密码为："+password, null, null);
                if("0".equals(smsReturn) || "1".equals(smsReturn)){
                    SmsSendLog smsSendLog = new SmsSendLog();
                    smsSendLog.setMobile(mobile);
                    smsSendLog.setContent("密码为："+password);
                    smsSendLogService.add(smsSendLog);
                }
                if(companyId>0){
                    UserCompanyRef ref=new UserCompanyRef();
                    ref.setCompanyId(companyId);
                    ref.setCompanyUserId(userId);
                    companyUserService.addUserCompanyRef(ref);
                }
                CompanyRole companyRole=companyRoleService.selectDefault(companyId);
                if(companyRole!=null){
                    CompanyUserRole ref = new CompanyUserRole();
                    ref.setCompanyRoleId(companyRole.getCompanyRoleId());
                    ref.setCompanyUserId(userId);
                    companyUserService.addCompanyUserRole(ref);
                }
            }else{
                respMap=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL,ERROR_VALUE_MSG_TYPE_ERROR,null,"添加用户失败");
            }
        }catch(Exception e){
            respMap=packageException(e);
        }
        return respMap;
    }
    
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> del(Long userId){
        Map<String, String> respMap = new HashMap<String, String>(2);
        int ret =0;
        try{
            CompanyUser companyUser = (CompanyUser)session.getAttribute("user");
            Long companyId = companyUser.getLastCompanyId();
            ret = companyUserService.deleteRef(userId,companyId);
            companyUserService.clearUserRoleRef(userId,companyId);
            
            if(ret>0){
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"删除成功");
            }else{
                respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,"ErrorTelCode", "删除失败");
            }
        }catch(Exception e){
            respMap=packageException(e);
        }
        return respMap;
    }
    
    /**
     * 
     * 文件上传，读取号码文件入库(异步调用) <br/>
     * <p>
     * Description: 文件上传，读取号码文件入库(详细描述) <br/>
     * <p>
     * Author: huangb<br/>
     * <p>
     * Date: 2013-7-3-上午9:12:00<br/>
     * <p>
     * 
     * @param test
     * @param multipartRequest
     * @return
     * 
     */
    @RequestMapping("/readfile")
    @ResponseBody
    public void readFile(HttpServletRequest request,HttpServletResponse response,MultipartFile userFile)
    {
        List<String[]> errorlist =new ArrayList<String[]>();
        System.out.println("userFile="+userFile);
        String result = "";
//        List<String> errorlist = new ArrayList<String>();
        int totalCount = 0;
        int successCount = 0;
        int eroorCount = 0;
        String errorCardNums = "";
        String msgType = "error";
        String opResult = "1";
        String url = "";
        String savePath = "";
        if(PwtzConstants.THE_SERVER_TYPE==1){
            savePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
        }else{
            savePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
            savePath = savePath.replaceAll("\\\\", "/");    //本地
        }
//        savePath = savePath.replaceAll("/", "\\\\");    //服务器
        try
        {
            if (_log.isInfoEnabled())
            {
                _log.info("开始上传文件");
            }
            String prefix = "";
            String fileName = "";
            String newFileName = "";

            fileName = userFile.getOriginalFilename();
            prefix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            newFileName = System.currentTimeMillis() + PwtzUtils.getRandomNumber(4)+ prefix;
            url = savePath + newFileName;
            BufferedInputStream in = new BufferedInputStream(userFile.getInputStream());
            File file = new File(savePath);
            if  (!file .exists()  && !file .isDirectory())      
            {       
                file .mkdirs();    
            }
//            System.out.println(url);
            FileOutputStream out = new FileOutputStream(new File(url));
            BufferedOutputStream output = new BufferedOutputStream(out);
            Streams.copy(in, output, true);

            List<String[]> list = null;
            if (prefix.endsWith(".xls") || prefix.endsWith(".xlsx"))
            {
                list = ExcelUtil.readExcel(new File(url));
            }
            
            try
            {
                if (list != null && list.size() > 0)
                {
                    totalCount = list.size();
//                    list = removeDuplicate(list);
                    int syzs =list.size();
                    System.out.println(list);
                    for(String[] str:list){
                        if(str.length>2){
                            Map<String, String> map = add(str[0],str[1],str[2]);
                            if(!"0".equals(map.get(ERROR_KEY_OP_RESULT))){
                                String [] newStr = new String[4];
                                newStr[0]= str[0];
                                newStr[1]= str[1];
                                newStr[2]= str[2];
                                newStr[3]= map.get(ERROR_KEY_MSG_DESC);
                                errorlist.add(newStr);
                            }
                        }else{
                            String [] newStr = new String[4];
                            if(str.length>0)
                            newStr[0]= str[0];
                            if(str.length>1)
                            newStr[1]= str[1];
                            newStr[3]= "输入不完整";
                            errorlist.add(newStr);
                        }
                    }
                    if (errorlist != null && errorlist.size() > 0)
                    {
                        eroorCount = errorlist.size();
                    }
                    if (list != null && list.size() > 0)
                    {
                        successCount = syzs - eroorCount;
                    }
                }
            }
            catch (Exception e)
            {
                _log.error(ExceptionUtils.getStackTrace(e));
            }
            if (totalCount > 0 && successCount > 0)
            {
                result = "批量入库成功!";
                msgType = "info";
                opResult = "0";
            }
            else if (totalCount == 0)
            {
                result = "批量入库失败,号码文件为空!";
                msgType = "info";
                opResult = "1";
            }
            else if (totalCount > 0 && successCount == 0)
            {
                result = "批量入库失败,文件号码无效!";
                msgType = "info";
                opResult = "2";
            }

            if (_log.isInfoEnabled())
            {
                _log.info(result);
            }
        }
        catch (IOException e)
        {
            result = "文件上传IO异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (Exception e)
        {
            result = "未知异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
//        return errorlist;
        writeJsonObject(
                request,
                response,
                "{\"msgDesc\":\"" + result + "\",\"msgType\":\"" + msgType + "\",\"opResult\":\"" + opResult
                        + "\",\"errorlist\":" + JsonUtils.bean2json(errorlist) + ",\"successCount\":\"" + successCount
                        + "\",\"eroorCount\":\"" + eroorCount + "\",\"totalCount\":\"" + totalCount + "\",\"addr\":\""
                        + url.replaceAll("\\\\", "/") + "\"}");
    }

    /**
     * 
     * 向客户端响应json数据 <br/>
     * <p>
     * Description: 向客户端响应json数据 <br/>
     * <p>
     * Author: yangzq<br/>
     * <p>
     * Date: 2013-7-3-下午1:57:18<br/>
     * <p>
     * 
     * @param request
     * @param resp
     * @param jsonData
     * 
     */
    private void writeJsonObject(HttpServletRequest request, HttpServletResponse resp, String jsonData)
    {
        System.out.println("jsonData="+jsonData);
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = null;
        try
        {
            pw = resp.getWriter();
            pw.print(jsonData);
            pw.flush();
        }
        catch (IOException e)
        {
            handleException(e);
        }
        finally
        {
            if (null != pw)
            {
                pw.close();
            }
        }
    }
    
    @RequestMapping(value = "/cheacin", method = RequestMethod.POST)  
    @ResponseBody
    public Map<String, String> cheacin(Long companyId){
        Map<String, String> respMap = new HashMap<String, String>(2);
        try{
        CompanyUser user = getUser();
        user.setLastCompanyId(companyId);
        CompanyUser newUser = new CompanyUser();
        newUser.setCompanyUserId(user.getCompanyUserId());
        newUser.setLastCompanyId(companyId);
        companyUserService.update(newUser);
        session.setAttribute("user", user);
        List<String> actionList=getCurrentAction();
        session.setAttribute("actionList", actionList);
        CompanyRole role= companyRoleService.selectCurrentRole(companyId, user.getCompanyUserId()).get(0);
        Company company=companyService.load(companyId);
        /*if(session.getAttribute("isSuper")!=null)
        {
            if(role.getIsSuper()==1){
                session.setAttribute("isSuper", true);
            }else{
                session.setAttribute("isSuper", false);
            }
            
        }*/
        if(session.getAttribute("actionCodes")!=null)
        {
//            Set<String> actionCodes =companyRoleService.getUserActionCodes(user.getCompanyUserId(), companyId);
            session.setAttribute("actionCodes", actionList);
        }
        if(session.getAttribute("companyEnable")!=null)
        {
            if(company.getStatus()==1){
                session.setAttribute("companyEnable", true);
            }else{
                session.setAttribute("companyEnable", false);
            }
        }
            respMap = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null,"进入该单位成功");
        }catch(Exception e){
            respMap=packageException(e);
        }
        return respMap;
    }
    
    
    @RequestMapping(value="/getuserbycompanyid",method=RequestMethod.POST)
    @ResponseBody
    public List<CompanyUser> list(Long companyId) throws PwtzException{
        PaginationList<CompanyUser> list = new PaginationList<CompanyUser>();
        List<CompanyUser> ret=null;
        try
        {
            if(companyId==0){
                ret = companyUserService.selectUserByCompanyIds(companyId);
            }else{
                list=companyUserService.selectUseByCompanyId(companyId, 0, 0);
                if(list!=null){
                    ret = list.getRecords();
                }
            }
        }
        catch (PwtzDatabaseException e)
        {
            e.printStackTrace();
        }
        return ret;
    }
}